package com.wryyyyy.controller;

import cn.hutool.core.map.MapUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.wryyyyy.dto.Result;
import com.wryyyyy.entity.*;
import com.wryyyyy.repository.SpaceRepository;
import com.wryyyyy.service.IModelService;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wryyyyy
 * @since 2024-06-18
 */
@Slf4j
@RestController
@RequestMapping("/model")
public class ModelController {
    @Resource
    private IModelService modelService;

    @Resource
    private GridFsTemplate gridFsTemplate;

    @Resource
    private SpaceRepository spaceRepository;

    /**
     * 根据factoryId获取设备模型
     * @param factoryId 污水厂Id
     * @return 模型列表
     */
    @GetMapping("/list")
    public Result getEditList(
            @RequestParam("factoryId") String factoryId
    ) {
        Space space = spaceRepository.findByFactoryId(factoryId);
        return Result.ok(space);
    }

    /**
     * 提交
     */
    @PostMapping("/submit")
    public Result submit(@RequestBody Map<String, Object> params) {
        String factoryId = MapUtil.get(params, "factoryId", String.class);
        CommonModel[] commonModels = MapUtil.get(params, "commonModels", CommonModel[].class);
        SelfModel[] selfModels = MapUtil.get(params, "selfModels", SelfModel[].class);
        Pipe[] pipes = MapUtil.get(params, "pipes", Pipe[].class);
        Label[] labels = MapUtil.get(params, "labels", Label[].class);

        Space space = spaceRepository.findByFactoryId(factoryId);
        if(space == null)
            space = new Space();
        space.setFactoryId(factoryId);
        space.setCommonModels(Arrays.asList(commonModels));
        space.setSelfModels(Arrays.asList(selfModels));
        space.setPipes(Arrays.asList(pipes));
        space.setLabels(Arrays.asList(labels));
        spaceRepository.save(space);

        return Result.ok(space);
    }

    @PostMapping("/upload")
    public Result upload(@RequestParam("blob") MultipartFile blob) throws IOException {
        // 文件名
        String uuid = UUID.randomUUID().toString().replace("-","");
        uuid = uuid.substring(0, 10);
        String filename = "自定义模型" + uuid + ".glb";

        // grid fs
        InputStream inputStream = blob.getInputStream();
        ObjectId objectId = gridFsTemplate.store(inputStream, filename, "");
        String fileId = objectId.toString();

        SelfModel selfModel = new SelfModel();
        selfModel.setFilename(filename);
        selfModel.setFileId(fileId);
        return Result.ok(selfModel);
    }

    @GetMapping("/download")
    public ResponseEntity<org.springframework.core.io.Resource> download(@RequestParam("fileId") String fileId) throws IOException {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        assert gridFSFile != null;
        InputStream inputStream = gridFsTemplate.getResource(gridFSFile).getInputStream();

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + gridFSFile.getFilename() + "\"");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }
}
